<?php

namespace app\shop\admin;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use app\shop\model\PinModel;
use app\shop\model\GoodsModel;


class Pin extends Admin
{
    public function index()
    {
        $list = PinModel::getAllList();
        $item = $list->items();
        $page = $list->render();
        foreach ($item as $k=>$v){
            $item[$k]['time'] = $v['time']/3600;
        }
        $se_btn = [
            'title'=>'查看',
            'icon'=>'fa fa-fw fa-circle-o',
            'href'=>url('#', ['user_id' => '__user_id__'])
        ];
        return ZBuilder::make('table')
            ->setPageTitle('拼团管理')
            ->hideCheckbox()
            ->addColumns([
                ['goods_name','活动商品'],
                ['price','拼团价格'],
                ['num','成团人数'],
                ['time','拼团时间/小时'],
                ['right_button','操作']
            ])
            ->addTopButton('add')
            ->addRightButton('se',$se_btn)
            ->addRightButtons('edit,delete')
            ->setRowList($item)
            ->setPages($page)
            ->fetch();
    }

    public function add()
    {
        if(request()->isPost()){
            $this->store();
        }
        $goods_list = GoodsModel::getRes();
        return ZBuilder::make('form')
            ->addFormItems([
                ['select','goods_id','活动商品','',$goods_list],
                ['text','price','拼团价格',''],
                ['text','num','成团人数'],
                ['text','time','拼团时间','拼团持续时间，单位1小时'],
            ])
            ->setUrl(url('add'))
            ->fetch();
    }

    public function edit($id=0)
    {
        if(request()->isPost()){
            $this->store();
        }
        $data = PinModel::getOne($id);
        $data['time'] = $data['time']/3600;
        $goods_list = GoodsModel::getRes();
        return ZBuilder::make('form')
            ->addHidden('id')
            ->addFormItems([
                ['select','goods_id','活动商品','',$goods_list],
                ['text','price','拼团价格',''],
                ['text','num','成团人数'],
                ['text','time','拼团时间','拼团持续时间，单位1小时'],
            ])
            ->setFormData($data)
            ->setUrl(url('edit'))
            ->fetch();
    }

    public function delete($ids = 0)
    {
        $res = PinModel::del($ids);
        if($res){
            $this->success('删除成功',url('index'));
        }else{
            $this->error('删除失败');
        }
    }

    private function store()
    {
        $id = input('id',0);
        $data = input('post.');
        $validate = new \app\shop\validate\Pin();
        if(!$validate->check($data)){
            $this->error($validate->getError());
        }
        $data['time'] = intval($data['time']*3600);
        $res = PinModel::store($data, $id);
        if($res){
            $this->success('保存成功',url('index'));
        }else{
            $this->error('保存失败，请重试！');
        }
    }

}